package com.travel.travel_springboot_web.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Component
public class FileUtil {
    
    private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);
    
    @Value("${file.upload-dir}")
    private String uploadDir;
    
    public String saveFile(MultipartFile file) throws IOException {
        // 创建上传目录
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        
        // 生成新的文件名
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFilename = UUID.randomUUID().toString() + extension;
        
        // 保存文件
        File destFile = new File(dir.getAbsolutePath() + File.separator + newFilename);
        file.transferTo(destFile);
        
        // 返回访问URL
        return "/uploads/" + newFilename;
    }
    
    // 删除单个文件
    public boolean deleteFile(String fileUrl) {
        if (fileUrl == null || fileUrl.isEmpty()) {
            logger.warn("File URL is null or empty");
            return false;
        }
        
        try {
            // 从URL中获取文件名
            String fileName;
            if (fileUrl.contains("/uploads/")) {
                fileName = fileUrl.substring(fileUrl.lastIndexOf("/uploads/") + 9);
            } else {
                fileName = fileUrl;
            }
            
            File file = new File(uploadDir + File.separator + fileName);
            logger.info("Attempting to delete file: {}", file.getAbsolutePath());
            
            if (file.exists()) {
                boolean result = file.delete();
                logger.info("Deleting file: {}, result: {}", fileName, result);
                return result;
            } else {
                logger.warn("File not found: {}", file.getAbsolutePath());
                return false;
            }
        } catch (Exception e) {
            logger.error("Error deleting file: " + fileUrl, e);
            return false;
        }
    }
    
    // 批量删除文件
    public void deleteFiles(List<String> fileUrls) {
        if (fileUrls == null || fileUrls.isEmpty()) {
            logger.warn("No files to delete");
            return;
        }
        
        logger.info("Starting to delete {} files", fileUrls.size());
        for (String fileUrl : fileUrls) {
            try {
                boolean result = deleteFile(fileUrl);
                logger.info("Delete file result: {} for URL: {}", result, fileUrl);
            } catch (Exception e) {
                logger.error("Error deleting file: " + fileUrl, e);
            }
        }
    }
} 